package org.example.Servlet.TopicServlet;

import cn.hutool.json.JSONUtil;
import org.example.Dao.TopicDao;
import org.example.entity.Topic;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet("/admin/topic/findTopic")
public class FindTopicServlet extends HttpServlet {


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int tid = -1;
        if (!req.getParameter("tid").isEmpty()) {
            tid = Integer.parseInt(req.getParameter("tid"));
        }


        String title = req.getParameter("title");
        String beginDateStr = req.getParameter("beginDate");
        String endDateStr = req.getParameter("endDate");
        int status = Integer.parseInt(req.getParameter("status"));
        HttpSession session = req.getSession();
        // 日期字符串转换成日期
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date beginDate = null;
        Date endDate = null;
        TopicDao topicDao = new TopicDao();
        try {

            if (!beginDateStr.isEmpty()) {
                beginDate = simpleDateFormat.parse(beginDateStr);
            }

            if (!endDateStr.isEmpty()) {
                endDate = simpleDateFormat.parse(endDateStr);
            }

            List<Topic> topicList = topicDao.find(tid, title, beginDate, endDate, status);
            session.setAttribute("findOptionMsg", "");
            resp.getWriter().write(JSONUtil.toJsonStr(topicList));
        } catch (Exception e) {
            System.out.println("find topic error ==> " + e.getMessage());
            session.setAttribute("findOptionMsg", "查询失败");
        }

    }
}
